<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>客户管理</title>

	<!--todo：这是导出的按钮样式-->
	<style>
		#downloadLink:hover{
			border: 1px solid #adadad;
			margin-top: 2px;
			border-radius: 3px;
			background-color: #e7e6e7;
			text-decoration: none; /*将超链接的下划线去掉*/
		}

		#downloadLink{
			text-decoration: none; /*将超链接的下划线去掉*/
			margin: 1px 0px 1px 1px;
			padding: 7px;
			font-size: 12px;
			border: none;
			cursor: pointer;
			color: #3c3c3c;
			background-color: #fdfcfd;
		}
		/*
                a[id="downloadLink"] span#myIncon-export{
                    width: 12px;
                    height: 12px;
                    background-image: url('/static/static/images/myIcon/export.png');
                }
                */
	</style>

<link rel="stylesheet" type="text/css" href="/static/insdep/insdep.easyui.min.css"></link>
<link rel="stylesheet" type="text/css" href="/static/insdep/icon.css"></link>
<link rel="stylesheet" type="text/css" href="/static/insdep/custom.css"></link>
<script type="text/javascript" src="/static/jquery-easyui-1.5/jquery.min.js"></script>
<script type="text/javascript" src="/static/jquery-easyui-1.5/jquery.easyui.min.js"></script>
<script type="text/javascript" src="/static/jquery-easyui-1.5/locale/easyui-lang-zh_CN.js"></script>
<script type="text/javascript">

	var url;

	function formatEdit(val,row){
		return "<a href=\"javascript:openRoleChooseDialog('"+row.roles+"',"+row.id+")\"><img style='margin-top: 4px' src='/static/images/edit.gif' /></a>";
	}
	
	function openRoleChooseDialog(roles,customerId){
		var rolesArr=roles.split(",");
		$("#roleSetDialog").dialog("open").dialog("setTitle","选择角色");
		$("#roleDg").datagrid({
					url:'/admin/role/listAll',
					onLoadSuccess:function(data){
						var selectedRows=$("#roleDg").datagrid('getRows');
						for(var i=0;i<selectedRows.length;i++){
							var name=selectedRows[i].name;
							if($.inArray(name, rolesArr)>=0){
								$("#roleDg").datagrid('checkRow',i);
							}  
						}
					}
		});
		$("#customerId").val(customerId);
	}
	
	function saveRoleSet(){
		var customerId=$("#customerId").val();
		var selectedRows=$("#roleDg").datagrid("getSelections");
		var strRoleIds=[];
		for(var i=0;i<selectedRows.length;i++){
			strRoleIds.push(selectedRows[i].id);
		}
		var roleIds=strRoleIds.join(",");
		$.post("/admin/customer/saveRoleSet",{roleIds:roleIds,customerId:customerId},function(result){
			if(result.success){
				closeRoleSetDialog();
				$("#dg").datagrid("reload");
			}else{
				$.messager.alert("系统提示","提交失败，请联系管理员！");
			}
		},"json");
	}
	
	function closeRoleSetDialog(){
		 $("#roleSetDialog").dialog("close");
	 }

	function deleteCustomer(){
		var selectedRows=$("#dg").datagrid("getSelections");
		if(selectedRows.length==0){
			 $.messager.alert("系统提示","请选择要删除的数据！");
			 return;
		 }
		var strIds=[];
		 for(var i=0;i<selectedRows.length;i++){
			 strIds.push(selectedRows[i].id);
		 }
		 var ids=strIds.join(",");
		 $.messager.confirm("系统提示","您确定要删除这<font color=red>"+selectedRows.length+"</font>条数据吗？",function(r){
				if(r){
					$.post("/admin/customer/delete",{ids:ids},function(result){
						if(result.success){
							 $.messager.alert("系统提示","数据已成功删除！需要<b>导出</b>请<b>刷新</b>页面哦~");
							 $("#dg").datagrid("reload");
						}else{
							$.messager.alert("系统提示",result.errorInfo);
						}
					},"json");
				} 
	   });
	}

	function openCustomerAddDialog(){

		$("#dlg").dialog("open").dialog("setTitle","添加客户信息");
		url="/admin/customer/save";
	}
	
	function openCustomerModifyDialog(){

		var selectedRows=$("#dg").datagrid("getSelections");
		 if(selectedRows.length!=1){
			 $.messager.alert("系统提示","请选择一条要修改的数据！");
			 return;
		 }
		 var row=selectedRows[0];
		 $("#dlg").dialog("open").dialog("setTitle","修改客户信息");
		 $("#fm").form("load",row);
		 $("#customerName").attr("readonly","readonly")
		 url="/admin/customer/save?id="+row.id;
	 }

	function saveCustomer(){
		 $("#fm").form("submit",{
			url:url,
			onSubmit:function(){
				return $(this).form("validate");
			},
			success:function(result){
				var result=eval('('+result+')');
				if(result.success){
					$.messager.alert("系统提示","保存成功！需要<b>导出</b>请<b>刷新</b>页面哦~");
					resetValue();
					$("#dlg").dialog("close");
					$("#dg").datagrid("reload");
				}else{
					$.messager.alert("系统提示",result.errorInfo);
				}
			}
		 });
	 }

	function resetValue(){
		 $("#name").val("");
		 $("#contact").val("");
		 $("#number").val("");
		 $("#address").val("");
		 $("#remarks").val("");
	 }

	function closeCustomerDialog(){
		$("#dlg").dialog("close");
		 resetValue();
	}
	 
	function searchCustomer(){
		$("#dg").datagrid('load',{
			"name":$("#s_name").val() 
		});
	}

	$(function () {  
		 
		 $("#dg").datagrid({  
		        //双击事件  
		        onDblClickRow: function (index, row) {  
		        	$("#dlg").dialog("open").dialog("setTitle","修改客户信息");
			   		 $("#fm").form("load",row);
			   		 $("#customerName").attr("readonly","readonly")
			   		 url="/admin/customer/save?id="+row.id;
		        }  
		 });  
		 
		 // 自动分析联系人
		 $('#remarks').bind('paste',function(e){
		        var pastedText = undefined;
		        if (window.clipboardData && window.clipboardData.getData) { 
		            pastedText = window.clipboardData.getData('Text');
		        } else {
		            pastedText = e.originalEvent.clipboardData.getData('Text');
		        }
		        
		        var person;
		        if(pastedText.indexOf("，") >=0){
		        	person = pastedText.split("，");
		        }else{
		        	person = pastedText.split(",");
		        }
		        
		        if (person.length >= 3) {
		        	 $("#name").val(person[0]);
		    		 $("#contact").val(person[0]);
		    		 $("#number").val(person[1]);
		    		 $("#address").val(person[2]);
		        }
		    });
	 });
</script>

	<!--todo:导出Excel-->
	<script type="text/javascript">

		<!--统计点击导出的次数，刷新归零-->
		// 从本地存储获取计数的值，如果不存在则初始化为0
		let count = localStorage.getItem('count')? parseInt(localStorage.getItem('count')) : 0;

		const countButton = document.getElementById('downloadLink');
		const countValueSpan = document.getElementById('countValue');

		countValueSpan.textContent = count;

		countButton.addEventListener('click', function () {
			count++;
			// 将更新后的计数保存到本地存储
			localStorage.setItem('count', count);
			countValueSpan.textContent = count;
		});

		// 当页面重新加载（刷新）时，重新读取本地存储中的计数（或者初始化为0）
		window.addEventListener('load', function () {
			console.log("页面加载，准备重置计数");
			// 将本地存储中的count值重置为0
			localStorage.setItem('count', 0);
			count = 0;
			console.log("重新读取到的本地存储中的计数:", count);
			countValueSpan.textContent = count;
			console.log("已更新页面显示的计数");
		});
/*
		// 隐藏错误信息显示元素
		document.getElementById('errorMessage').style.display = 'none';
		*/
/* //文件导入数据库
		function uploadFile() {
			const fileInput = document.getElementById('fileUpload');
			const file = fileInput.files[0];
			if (!file) {
				showErrorMessage('请选择要上传的文件');
				return;
			}

			const formData = new FormData();
			formData.append('file', file);

			fetch('http://localhost:8080/upload', {
				method: 'POST',
				body: formData
			})
					.then(response => response.json())
					.then(data => {
						if (data.status === 200) {
							alert(data.message + ', 花费时间: ' + data.elapsedTime);
						} else {
							showErrorMessage(data.message);
						}
					})
					.catch(error => {
						console.error('上传文件出错:', error);
						showErrorMessage('上传文件时发生错误，请检查网络连接或稍后再试');
					});
		}
*/

		function downloadFile() {
			fetch('http://localhost:8082/admin/customer/download')
					.then(response => {
						console.log("响应头信息:", response.headers);
						console.log("响应数据类型:", response.type);
						if (response.ok) {
							return response.blob();
						} else {
							return response.text().then(text => {
								throw new Error('文件下载失败，原因: ' + text);
							});
						}
					})
					.then(blob => {
						const downloadLink = document.getElementById('downloadLink');
						downloadLink.href = URL.createObjectURL(blob);
						if(count++ === 0){
							$.messager.alert("首次有点问题😪","温馨提示： 在浏览器的下载列表中可查看导出的内容。但是每次刷新页面的第一次可能导出失败，所以需要多导一次（这个bug修不好了，理解一下💦）")
						}else {
							$.messager.alert("导出成功🤏！","温馨提示： 在浏览器的下载列表中可查看导出的内容。辛苦您多点一次啦😊😊")
						}

					})
					.catch(error => {
						console.error('下载文件出错:', error);
						showErrorMessage('下载文件时发生错误，请检查网络连接或稍后再试，详细原因: ' + error.message);
					});
		}
/*
		function showErrorMessage(message) {
			const errorMessageDiv = document.getElementById('errorMessage');
			errorMessageDiv.textContent = message;
			errorMessageDiv.style.display = 'block';
		}
		*/
	</script>

</head>
<body style="margin: 1px">
<table id="dg" title="客户管理" class="easyui-datagrid"
   fitColumns="true" pagination="true" rownumbers="true" 
   url="/admin/customer/list" fit="true" toolbar="#tb">
   <thead>
   	<tr>    
   	    <th field="cb" checkbox="true" align="center"></th>
   		<th field="id" width="20" align="center">编号</th>
   		<th field="name" width="100" align="center">客户名称</th>
   		<th field="contact" width="50" align="center">联系人</th>
   		<th field="number" width="50" align="center">联系电话</th>
   		<th field="address" width="150" align="center">联系地址</th>
   		<th field="remarks" width="150" align="center">备注</th>
   	</tr>
   </thead>
 </table>
 
 <div id="tb">
 	<div>
 		<a href="javascript:openCustomerAddDialog()" class="easyui-linkbutton" iconCls="icon-add" plain="true">添加</a>
 		<a href="javascript:openCustomerModifyDialog()" class="easyui-linkbutton" iconCls="icon-edit" plain="true">修改</a>
 		<a href="javascript:deleteCustomer()" class="easyui-linkbutton" iconCls="icon-remove" plain="true">删除</a>

		<!--todo：导出EXCEL，就这样吧，后端很多bug，插入之后帅新以下页面就可以正确导出啦，至于为什么，我也解决不了啊-->
		<a href="#" id="downloadLink" onclick="downloadFile()">📍 导出Excel</a>
<!--
		&lt;!&ndash; 新增用于显示错误信息的元素 &ndash;&gt;
		<div class="error-message" id="errorMessage"></div>
-->
		<!--<a href="javascript:downloadFile()" class="easyui-linkbutton" iconCls="icon-save" plain="true" title="todo">导出为Excel</a>-->
 	</div> 
 	<div>
 		&nbsp;客户名称：&nbsp;<input type="text" id="s_name" size="20" class="custom-text" onkeydown="if(event.keyCode==13) searchCustomer()"/>
 		<a href="javascript:searchCustomer()" class="easyui-linkbutton" iconCls="icon-search" plain="true">搜索</a>
 	</div>                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  
 </div>
 
 <div id="dlg" class="easyui-dialog" style="width:500px;height:350px;padding: 10px 20px"
   closed="true" buttons="#dlg-buttons" data-options="onClose:function(){resetValue()}">
   
   <form id="fm" method="post">
   	<table cellspacing="8px">
   		<tr>
   			<td>客户名称：</td>
   			<td><input type="text" id="name" name="name" class="easyui-validatebox custom-text" required="true" style="width: 250px"/></td>
   		</tr>
   		<tr>
   			<td>联系人：</td>
   			<td><input type="text" id="contact" name="contact" class="easyui-validatebox custom-text"  required="true" style="width: 250px"/></td>
   		</tr>
   		<tr>
   			<td>联系电话：</td>
   			<td><input type="text" id="number" name="number" class="easyui-validatebox custom-text"  required="true" style="width: 250px"/></td>
   		</tr>
   		<tr>
   			<td>联系地址：</td>
   			<td><input type="text" id="address" name="address" class="easyui-validatebox custom-text"  required="true" style="width: 250px"/></td>
   		</tr>
   		<tr>
   			<td valign="top">备注：</td>
   			<td>
   				<textarea rows="5" cols="40" id="remarks" name="remarks"></textarea>
   			</td>
   		</tr>
   	</table>
   </form>
 </div>
 
 <div id="dlg-buttons">
 	<a href="javascript:saveCustomer()" class="easyui-linkbutton" iconCls="icon-ok">保存</a>
 	<a href="javascript:closeCustomerDialog()" class="easyui-linkbutton" iconCls="icon-cancel">关闭</a>
 </div>
</body>
</html>